package com.gandong8.trace.tool.util;

import org.springframework.cglib.beans.BeanCopier;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BeanUtil {

    private static Map<String, BeanCopier> beanCache = new HashMap<>();

    public static Object copy(Object source, Class<?> targetClazz){
        try {
            return copy(source, targetClazz.newInstance());
        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Object copy(Object source, Object target){
        String mapKey = getKey(source.getClass(), target.getClass());
        BeanCopier beanCopier;
        if (beanCache.containsKey(mapKey)) {
            beanCopier = beanCache.get(mapKey);
        } else {
            beanCopier = BeanCopier.create(source.getClass(), target.getClass(), false);
            beanCache.put(mapKey, beanCopier);
        }
        beanCopier.copy(source, target, null);
        return target;
    }

    public static List<Object> copyList(List<Object> sourceList, Class<?> targetClazz){
        List<Object> targetList = new ArrayList<>();
        for (Object obj : sourceList) {
            Object targetObject ;
            try {
                targetObject = targetClazz.newInstance();
            } catch (InstantiationException | IllegalAccessException e) {
                e.printStackTrace();
                return null;
            }
            copy(obj, targetObject);
            targetList.add(targetObject);
        }
        return targetList;
    }

    public static List<Object> copyList(List<Object> sourceList, List<Object> targetList){
        return copyList(sourceList, targetList.get(0).getClass());
    }

    private static String getKey(Class<?> sourceClazz, Class<?> targetClazz) {
        return sourceClazz.getCanonicalName() + "_" + targetClazz.getCanonicalName();
    }
}
